<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/3/7 10:40
 */
declare(strict_types=1);

namespace App\Service\Auth;

use App\Bean\JwtUserBean;
use App\Bean\OnlineUserBean;
use App\Service\BaseService;
use App\Utility\EncryptUtils;
use App\Utility\Log\Log;
use App\Utility\Redis\RedisUtil;
use App\Utility\StringUtils;
use EasySwooleApi\Core\Request\Request;

class OnlineUserService extends BaseService
{
    /**
     * 保存在线用户信息
     *
     * @param JwtUserBean $jwtUserBean
     * @param string      $token
     * @param Request     $request
     *
     * @throws \App\Utility\Redis\Exception\RedisException
     */
    public function save(JwtUserBean $jwtUserBean, string $token, Request $request)
    {
        $user    = $jwtUserBean->getUser()->toArray(false, false);
        $deptArr = $user['dept'] ?: [];
        $dept    = $deptArr['name'] ?? '';
        $ip      = $request->ip();
        $browser = StringUtils::getBrowser($request);
        // todo::
        $address = '';
        try {
            $onlineUserBean = new OnlineUserBean();
            $onlineUserBean->setUsername($jwtUserBean->getUsername());
            $onlineUserBean->setNickname($jwtUserBean->getUser()->nickName);
            $onlineUserBean->setDept($dept);
            $onlineUserBean->setBrowser($browser);
            $onlineUserBean->setIp($ip);
            $onlineUserBean->setAddress($address);
            // todo::
            $onlineUserBean->setKey(EncryptUtils::desEncrypt($token));
            $onlineUserBean->setLoginTime(time());
        } catch (\Throwable $t) {
            Log::error($t->getMessage());
        }

        /** @var TokenService $tokenService */
        $tokenService = app(TokenService::class);
        $loginKey     = $tokenService->loginKey($jwtUserBean->getUsername(), $token);
        $value        = json_encode($onlineUserBean->toArray());
        $ttl          = config('jwt.token-validity-in-seconds');
        RedisUtil::set($loginKey, $value, ['PX' => $ttl]);
    }

    /**
     * 退出登录
     *
     * @param string $token
     */
    public function logout(string $username, string $token)
    {
        /** @var TokenService $tokenService */
        $tokenService = app(TokenService::class);
        $loginKey     = $tokenService->loginKey($username, $token);
        RedisUtil::del($loginKey);
    }

    public function getOne(string $key)
    {
        $json = RedisUtil::get($key);
        if ($json) {
            $arr = json_decode($json, true);
            return new OnlineUserBean($arr);
        }

        return null;
    }
}
